package cn.itcast.itcaststore.web.servlet.manager;

import cn.itcast.itcaststore.domain.Products;
import cn.itcast.itcaststore.exception.AddProductException;
import cn.itcast.itcaststore.serive.ProductService;
import cn.itcast.itcaststore.serive.impl.ProductServiceImpl;
import cn.itcast.itcaststore.utils.FileUploadUtils;
import cn.itcast.itcaststore.utils.IdUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/admin/addProduct")
public class AddProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建Product对象，用于封装提交的数据
        Products p = new Products();
        HashMap<String, String> map = new HashMap<>();
        // 通过IdUtils工具类生成UUID，封装成商品的Id
        map.put("id", IdUtils.getUUID());
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        // 设置临时文件存储位置
        dfif.setRepository(new File(this.getServletContext().getRealPath("/temp")));
        // 设置上传文件缓存大小为10m
        dfif.setSizeThreshold(1024*1024*10);
        // 创建上传组价
        ServletFileUpload upload = new ServletFileUpload(dfif);
        // 处理上传文件中文乱码
        upload.setHeaderEncoding("utf-8");
        try{
            // 解析request得到所有的FileItem
            List<FileItem> items = upload.parseRequest(request);
            // 遍历所有FileItem
            for (FileItem item : items){
                // 判断当前是否是上传组件
               if (item.isFormField()){
                   // 不是上传组件
                   String fieldName = item.getFieldName();//获取组件名称
                   String value = item.getString("utf-8");//解决乱码问题
                   map.put(fieldName,value);
               }else {
                   // 是上传组件
                   //得到上传文件真是名称
                   String fileName = item.getName();
                   fileName = FileUploadUtils.subFileName(fileName);
                   // 得到随机名称
                   String randomName = FileUploadUtils.generateRandonFileName(fileName);
                   // 得到随机目录
                   String randomDir = FileUploadUtils.generateRandomDir(randomName);
                   //图片存储父目录
                   String imgurl_parent = "/productImg" + randomDir;
                   File parentDir = new File(this.getServletContext().getRealPath(imgurl_parent));
                   // 验证目录是否存在，如果不存在，创建出来
                   if (!parentDir.exists()){
                       parentDir.mkdirs();
                   }
                   // 拼接图片存放的地址
                   String imgurl = imgurl_parent + "/" + randomName;
                   map.put("imgurl",imgurl);
                   IOUtils.copy(item.getInputStream(),new FileOutputStream(new File(parentDir,randomName)));
                   item.delete();
               }
            }
        }catch (FileUploadException e){
            e.printStackTrace();
        }
        try {
            // 通过BeanUtils工具的populate()方法，将数据封装到javaBean中
            BeanUtils.populate(p,map);
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch (InvocationTargetException e){
            e.printStackTrace();
        }
        // 创建ProductService类的对象
        ProductService service = new ProductServiceImpl();
        try {
            // 调用service层方法完成添加商品操作
            service.addProduct(p);
            // 请求转发到"/listProduct"路径，查询所有商品并显示商品管理页首页
            response.sendRedirect(request.getContextPath() + "/admin/listProduct");
            return;
        }catch (AddProductException e){
            e.printStackTrace();
            response.getWriter().write("添加商品失败");
            return;
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
